package com.wn.config;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @author yellow Docter
 * @date 2022 -07-08
 * @desc
 *  MybatisConfig 的配置
 */
public class MybatisConfig {

    // 01 sqlSessionFactoryBean
    // SqlSessionFactoryBean 按到 sqlSession
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){

        SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
        //设置模型类的别名扫描
        ssfb.setTypeAliasesPackage("com.wn.bean");
        // 设置 mapper.xml文件位置,如果在同一目录下面可以省略
        //设置数据源
        ssfb.setDataSource(dataSource);

        return ssfb;
    }

    // 02 mapper 管理类
    //定义bean，返回MapperScannerConfigurer对象

    /**
     * MapperScannerConfigurer 这个对象会通过 com.wn.mapper的扫描
     *  把 mapper进行动态代理 生成代理对象,把这些对象添加到ioc容器中
     *  默认的id是首字符
     * @return
     */
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        msc.setBasePackage("com.wn.mapper");
        return msc;
    }

    @Bean
    public DataSourceTransactionManager dataSourceTransactionManager(DataSource dataSource){
        DataSourceTransactionManager sourceTransactionManager = new DataSourceTransactionManager(dataSource);
        return sourceTransactionManager;
    }

}
